package com.qcorm.core;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.log4j.Logger;


/**
 *
 * @param <T>
 */
public class BaseDao<T extends BaseModel> {
	static Logger logger = Logger.getLogger(BaseDao.class.getName());

	/**
	 * 添加记录
	 * @param item
	 * @return
	 */
	public int add(T item){
		Collections.sort(item.parameters, new SortByIsQueryCondition());
		SqlBuilder<T> sqlBuilder = new SqlBuilder<T>();
		String sql = sqlBuilder.buildAddSQL(item);
		return executeUpdate(sql, item);
	}
	
	/**
	 * 查第一条记录
	 * @param item
	 * @return
	 */
	public T toFirst(T item)
    {
		item.topCount = 1;
		SqlBuilder<T> sqlBuilder = new SqlBuilder<T>();
		String sql = sqlBuilder.buildQuerySQL(item);
        ArrayList<T> toListItems = executeQuery(sql, item);
        if(toListItems != null && !toListItems.isEmpty())
        {
        	return toListItems.get(0);
        }else{
        	return null;
        }
        
    }
	
	/**
	 * 更新记录
	 * @param item
	 * @return
	 */
	public int update(T item)
    {
		Collections.sort(item.parameters, new SortByIsQueryCondition());
		
		SqlBuilder<T> sqlBuilder = new SqlBuilder<T>();
		String sql = sqlBuilder.buildUpdateSQL(item);
        
		return executeUpdate(sql, item);
    }
	
	/**
	 * 删记录
	 * @param item
	 * @return
	 */
	public int delete(T item){
		SqlBuilder<T> sqlBuilder = new SqlBuilder<T>();


		//为了防止SQL注入或者写错删除条件等问题，删除数据，只能根据主键ID来删
		Boolean isItemLegal = false;
		for (DaoParameter p : item.parameters) {
			
			if (p.getParameterName().equals(item.keyName) && p.getIsWhereCondition()) {
				isItemLegal = true;
			}
		}
        
		if(!isItemLegal)
		{
			//非法的参数（没有主键ID）
			logger.error("Delete方法非法的参数：没有主键ID");
			return 0;
		}
		
		String sql = sqlBuilder.buildDeleteSQL(item);
		return executeUpdate(sql, item);
	}
		 
	
	
	/**
	 * 查列表
	 * @param item
	 * @return
	 */
	public List<T> toList(T item)
    {
		item.topCount = 0;
		
		SqlBuilder<T> sqlBuilder = new SqlBuilder<T>();
		String sql = sqlBuilder.buildQuerySQL(item);
        return executeQuery(sql, item);
    }
	
	
	
	/**
	 * 
	 * @param sql
	 * @param item
	 * @return
	 */
	private ArrayList<T> executeQuery(String sql, T item)    {
		
		DBUtil db = new DBUtil(item.dbType, item.dbName);
		ArrayList<T> resultList  = new ArrayList<T>();
		

		ArrayList<DaoParameter> whereCondition = new ArrayList();
		for(DaoParameter parameter : item.parameters){
			if(parameter.getIsWhereCondition()){
				whereCondition.add(parameter);
			}
		}
		
		ResultSet rs = db.executeQuery(sql, whereCondition);
		
		if(rs != null){
			
			try {
				resultList =  (ArrayList<T>) RsMapper.rsMapToEntityList(item.getClass(), rs);
			} catch (Exception e) {
				logger.error("executeQuery exception",e);
			} finally{
				db.close();
			}
		}
		return resultList;
    }
	
	
	
	
	/**
	 * 
	 * @param sql
	 * @param item
	 * @return
	 */
	private int executeUpdate(String sql, T item)    {
		
		DBUtil db = new DBUtil(item.dbType, item.dbName);
		
		int result = 0 ;
		
		try {
			result = db.executeUpdate(sql, item.parameters);
		} catch (Exception e) {
			logger.error("executeUpdate exception", e);
		}
		finally{
			db.close();
		}
		return result;
    }
}

/**
 * 排序
 */
class SortByIsQueryCondition implements Comparator<DaoParameter> {

	public int compare(DaoParameter p1, DaoParameter p2) {		
		int a = 0;
		int b = 0;
		if(p1.getIsWhereCondition()){
			a = 1;
		}
		if(p2.getIsWhereCondition()){
			b=1;
		}
		
		return a-b;
	}
}
	 
